package it.afs.worklog.application;

import it.afs.utils.PropertyManager;
import it.afs.worklog.User;

import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;

/**
 * @author Fanta
 */
public class LoginPage extends BasePage
{
	private WebMarkupContainer passwordPanel;
	private boolean newPassword = false;
	
	public LoginPage() {
		super();
		
		addComponents();
	}
	
	@Override
	protected void addComponents()
	{
		super.addComponents();
		
		
		Form<Void> form = new Form<Void>("form")
		{
			private static final long serialVersionUID = 2938278449450220650L;

			@Override
			protected void onSubmit()
			{
				String psw = get("password").getDefaultModelObjectAsString();
				if(newPassword) psw = PropertyManager.getValue("user.password.default");
				
				User user = getFactory().getDao().login(get("username").getDefaultModelObjectAsString(), psw);
				if(user != null)
				{
					if(newPassword)
					{
						user.setPassword(get("password").getDefaultModelObjectAsString());
						getFactory().getDao().set(user);
					}
					
					if(user.getPassword().equals(PropertyManager.getValue("user.password.default")))
					{
						passwordPanel.setVisible(true);
						get("password").setDefaultModelObject(null);
						get("password").modelChanged();
						error(getString("user.new"));
						newPassword = true;
					}
					else if(user.getLivello() >= 0)
					{
						WorkLogSession.getCurrentSession().setLoggedUser(user);
						setResponsePage(HomePage.class);
					}
					else
					{
						error(getString("login.error"));
					}
				}
				else
				{
					error(getString("login.error"));
				}
			}
		};
		add(form);
		
		PasswordTextField password, passwordRetype;
		
		form.add(new RequiredTextField<String>("username", new Model<String>()));
		form.add(password = new PasswordTextField("password", new Model<String>()));
		
		passwordPanel = new WebMarkupContainer("new-password");
		passwordPanel.setVisible(false);
		form.add(passwordPanel);
		
		passwordPanel.add(passwordRetype = new PasswordTextField("password-retype", new Model<String>()));
		
		form.add(new EqualPasswordInputValidator(password, passwordRetype));
		
		form.add(new FeedbackPanel("feedback"));
	}
	
}